<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyCityNewlyOpenedShopCHModel;
use App\Remote\Guanyuan\GuanyuanRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

class SysGyCityNewlyOpenedShopCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyCityNewlyOpenedShop';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 城市新开门店数据-》clickhouse ';

    public int $id;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        $fields = [
            "month",
            "daysPerMonth",
            "region",
            "province",
            "city",
            "cityClassification",
            "numberOfStoresInOperation",
            "newStoreOpenedThisMonth",
            "targetNumberOfNewStoresOpened",
            "newStoresOpenedThisYear",
            "setNewGoalsThroughoutTheYear",
        ];

        $last        = GyCityNewlyOpenedShopCHModel::query()->orderByDesc("id")->first();
        if ($last) {
            $this->id    = $last->id;
            $executeDate = Carbon::createFromDate($last->month)->subDay()->startOfMonth()->format("Y-m-d");
            GyCityNewlyOpenedShopCHModel::query()->where("month", ">=", $executeDate)->delete();
        } else {
            $this->id    = 0;
            $executeDate = "2023-01-01";
        }

        $todayDate = Carbon::now()->startOfMonth()->format("Y-m-d");
        while ($executeDate <= $todayDate) {
            $this->getOutput()
                 ->info("$executeDate 正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]");
            $data = GuanyuanRemote::sourceData(
                'h0e9547fd32d64fb5b07ea44',
                'o6a87fcd060b64f7c97fd2ff',
                [
                    [
                        'name'        => '月',
                        'filterType'  => 'EQ',
                        'filterValue' => [$executeDate]
                    ]
                ],
                0
            );

            $this->getOutput()->info("当月数据量 :  " . count($data["data"] ?? []));
            if ($data["data"]) {
                collect($data["data"])->each(function ($row) use (
                    $fields,
                    &$batchInsert,
                    $executeDate
                ) {
                    collect($row)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                        if (isset($fields[$key])) {
                            $insert[$fields[$key]] = $value;
                        } else {
                            return false;
                        }
                    });

                    $this->id = $this->id + 1;
                    GyCityNewlyOpenedShopCHModel::query()->insert(array_merge(
                            $insert, [
                            "createdAt" => time(),
                            "id"        => $this->id,
                            "updatedAt" => 0
                        ])
                    );
                });
            }

            $executeDate = Carbon::createFromTimestamp(strtotime($executeDate))->addMonth()->firstOfMonth()
                                 ->format("Y-m-d");
        }
        return 0;
    }
}
